<template>
	<view class="module flex_ZC">
		<!-- #ifdef H5 -->
			<uNavbar title="执照管理"> </uNavbar>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
			<image class="indexbg" :src="baseUrl +'/static/image/indexbg.png'" mode="aspectFill"></image>
		<view class="custom_box">
			<view :style="{height: statusBarHeight + 'px', backgroundColor: backgroundColor }"></view>
			<view class="custom_nav " :style="{height: titleHeight + 'px', backgroundColor: backgroundColor}">
				<image class="goback" :src="baseUrl +'/static/icon/i_left.png'" mode="aspectFill" @click="leftClick"></image>
				<text class="f28 c3">执照管理</text>
			</view>
		</view>
		<view :style="{height: statusBarHeight + titleHeight + 'px'}" style="width: 100%;"></view>
		<!-- #endif -->
		<view class="information_txt flex_Z">
			<text class="f48 c3 fw7">上传营业执照信息</text>
		</view>
		
		<view class="content padb30 flex_Z">
			<view class="  flex_Z">
				<view class="flex_dq">
					<text class="f28 c3 fw5">营业执照</text>
					<text class="tishi"> *</text>
				</view> 
				<text class="content_tip">请上传营业执照</text>
			</view>
			<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
				:maxCount="1" :maxSize="6 *1024 *1024" @oversize="overSize" width="300" height="170">
				<view class="content_r flex_c">
				<image :src="baseUrl +'/static/image/hyzz.png'" mode="aspectFit"></image>
			</view> 
			</u-upload>
		</view>
		<view class="content flex_Z">
			<view class="flex_dq">
				<text class="f28 c3 fw5">执照名称</text>
				<text class="tishi"> *</text>
			</view>
			<u--input placeholder="请输入执照名称" fontSize="14" color="#666666" border="none " v-model.trim="ocrLicenseInfo.license_name"
				clearable></u--input>
		</view>
		<view class="content flex_Z">
			<view class="flex_dq">
				<text class="f28 c3 fw5">统一社会信用代码</text>
				<text class="tishi"> *</text>
			</view>
			<u--input placeholder="请输入信用代码" fontSize="14" color="#666666" border="none " v-model.trim="ocrLicenseInfo.social_credit_code"
				clearable></u--input>
		</view>
		<view class="content flex_Z">
			<view class="flex_dq">
				<text class="f28 c3 fw5">法人代表姓名</text>
				<text class="tishi"> *</text>
			</view>
			<u--input placeholder="请输入法人姓名" fontSize="14" color="#666666" border="none " v-model.trim="ocrLicenseInfo.legal_person_name"
				clearable></u--input>
		</view>
		<view class="content flex_Z">
			<view class="flex_dq">
				<text class="f28 c3 fw5">营业期限</text>
				<text class="tishi"> *</text>
			</view>
			<view class="term_box flex_dq">
				<text v-if="!endTerm" class="change_state ">上传自动识别</text>
				<text :class="endTerm?'active':'change_state'">{{ocrLicenseInfo.business_term_start}}</text>
				<text :class="endTerm?'active':'change_state'" v-if="ocrLicenseInfo.business_term_end" > - {{ocrLicenseInfo.business_term_end}}</text>
			</view>
		</view>
		<view class="content flex_Z">
			<view class="flex_dq">
				<text class="f28 c3 fw5">注册地区</text>
				<text class="tishi"> *</text>
			</view>
			<text class="content_tip">需要与执照地址保持一致</text>
			<view class="xuanze flex_ld" @click="openAddress">
				<text :class=" areaState?'active':'change_state'">{{addressAll}}</text>
				<u-icon name="arrow-right" color="#666666" size="14"></u-icon>
			</view>
		</view>
		
		<view class="btns flex_ld" v-if="!modifyState">
			<text class="sign_out" @click="leftClick">上一步</text>
			<text class="service"  @click="$u.debounce(nextStep, 300)">下一步</text> 
		</view>
		
		<view class="btns flex_ld" v-else>
			<text class="service2" @click="confirmModify">确认修改</text>
		</view>
		<view class="empty3"></view>
		
		<atAddress ref="scroll" :level="3"   @change='chooseSuccess'></atAddress>
	</view>
</template>

<script>
	import {commonArea} from "../../api/other.js"
	import {baseURL} from "../../utils/request.js"
	import {aiBusinessLicense,settledDetails} from "../../api/join.js"
	export default {
		data() {
			return {
				statusBarHeight: 0, //状态栏高度
				titleHeight: 0, // 标题栏高度
				backgroundColor: '',
				baseUrl: this.$imageBaseUrl,
				
				imgurl:'',//图片
				addressAll:'请选择所在区域',//合并地址
				halfRoadRoute:'',//半路经图片
				areaState: false, //是否选择地区
				endTerm:false, //开始营业期限
				modifyState:false, //是否通过修改按钮进入
				fileList1: [],
				ocrLicenseInfo:{}, //ocr识别信息
				
			}
		},
		onReady() {
			// #ifdef MP-WEIXIN 
			uni.getSystemInfo({
				success: res => {
					this.statusBarHeight = res.statusBarHeight
					console.log(this.statusBarHeight);
				}
			})
			const custombar = uni.getMenuButtonBoundingClientRect();
			this.titleHeight = (custombar.top - this.statusBarHeight) * 2 + custombar.height
			console.log(this.titleHeight);
			// #endif

		},
		onLoad(e) {
			console.log(e);
			this.modifyState = e.modify
			this.applicationDetails()
		},
		onShow() {
			if (uni.getStorageSync('ocrLicenseInfo')) {
				this.endTerm = true
				this.ocrLicenseInfo = uni.getStorageSync('ocrLicenseInfo')
				this.addressAll = uni.getStorageSync('ocrLicenseInfo').addressAll
			}
		},
		methods: {
			leftClick() {
				//获取页面栈的长度
				const canNavBack = getCurrentPages()
				console.log(canNavBack.length);
				// 判断是否刷新了浏览器，刷新了浏览器，页面栈只有当前一个
				if (canNavBack.length > 1) {
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.switchTab({
						url: '/pages/index/cloudCatIndex'
					})
				}
			},
			//打开地址选择器
			openAddress() {
				// console.log(this.$refs.scroll.)
				this.$refs.scroll.open()
			},
			//地址选择成功
			chooseSuccess(e) {
				console.log('所选择的地址信息:', e)
				this.addressAll = ''
				this.areaState = true
				let value = e.value;
				this.ocrLicenseInfo.province_id = e.value[0].id
				this.ocrLicenseInfo.city_id = e.value[1].id
				this.ocrLicenseInfo.county_id = e.value[2].id
				
				for (let i = 0; i < value.length; i++) {
					if (this.addressAll != value[i].name) {
						if (value[i].name != '县') {
							this.addressAll += value[i].name + ' '
						}
					}
				}
				console.log(this.addressAll);
			},
			// 截取半路经
			getPathAfterCom(url) {
			  const parts = url.split('.com');
			  return parts.length > 1 ? parts[1] : '';
			},
			
			// 入驻申请详情
			applicationDetails(){
				settledDetails().then(res=>{
					console.log(res);
					if(res.code == 1){
						this.areaState = true
						if(res.data.seller_auth != null){
							this.addressAll = res.data.seller_auth.full_address
							let kkk = res.data.seller_auth;
							let aaaa = {
								license_name:kkk.license_name,
								social_credit_code:kkk.social_credit_code,
								legal_person_name:kkk.legal_person_name,
								business_term_start:kkk.business_term_start,
								business_term_end:kkk.business_term_end,
								company_address:kkk.company_address,
								province_id:res.data.province_id,
								city_id:res.data.city_id,
								county_id:res.data.county_id,
							};
							if(kkk.business_term_end){
								this.endTerm = true
							}
							this.ocrLicenseInfo = aaaa;
							this.fileList1.push({'thumb':kkk.business_license,'status':'success'})
							this.halfRoadRoute = this.getPathAfterCom(kkk.business_license)
						}
					}
				})
			},
			// 超出提示
			overSize(event){
				// console.log(event);
				uni.$u.toast('图片过大,请重新上传!')
			},
			
			// 删除图片
			deletePic(event) {
				console.log(event);
				this[`fileList${event.name}`].splice(event.index, 1);
				this.imgurl = ''
				this.halfRoadRoute = ''
			},
			// 新增图片
			async afterRead(event) {
				console.log(event);
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen, 1, Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
				uni.hideLoading();
			},
			uploadFilePromise(url) {
				console.log(url);
				return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
						url: baseURL + `localSeller/common/upload`,
						filePath: url,
						name: 'file',
						header: {
							"ba-user-token": uni.getStorageSync("token") || ''
						},
						success: (res) => {
							console.log(JSON.parse(res.data))
							let datainfo = JSON.parse(res.data);
							if (datainfo.code == 1) {
								this.imgurl = datainfo.data.full_url
								this.halfRoadRoute = datainfo.data.url
								this.distinguishOcr()
								setTimeout(() => {
									resolve(res.data.data);
								}, 1000);
							} else {
								this.fileList1 = []
								uni.$u.toast(datainfo.msg);
							}
						}
					});
				});
			},
			// OCR识别
			distinguishOcr(){
				uni.showLoading({
					title: '加载中'
				});
				let data = {
					image:this.imgurl
				};
				aiBusinessLicense(data).then(res=>{
					console.log(res);
					uni.hideLoading();
					if(res.code == 1){
						this.ocrLicenseInfo.business_term_end = res.data.business_term_end
						this.ocrLicenseInfo.business_term_start = res.data.business_term_start
						this.ocrLicenseInfo.company_address = res.data.company_address
						this.ocrLicenseInfo.legal_person_name = res.data.legal_person_name
						this.ocrLicenseInfo.license_name = res.data.license_name
						this.ocrLicenseInfo.social_credit_code = res.data.social_credit_code
						this.endTerm = true
					}
				})
			},
			
			// 规则校验
			ruleValidation() {
				if (uni.$u.test.isEmpty(this.halfRoadRoute)) {
					uni.$u.toast('请上传营业执照');
					return false;
				}
				if (uni.$u.test.isEmpty(this.ocrLicenseInfo.license_name)) {
					uni.$u.toast('请输入执照名称');
					return false;
				}
				if (uni.$u.test.isEmpty(this.ocrLicenseInfo.social_credit_code)) {
					uni.$u.toast('请输入信用代码');
					return false;
				}
				if (uni.$u.test.isEmpty(this.ocrLicenseInfo.legal_person_name)) {
					uni.$u.toast('请输入法人姓名');
					return false;
				}
				if (uni.$u.test.isEmpty(this.ocrLicenseInfo.business_term_start)) {
					uni.$u.toast('营业期限不能为空');
					return false;
				}
				if (uni.$u.test.isEmpty(this.ocrLicenseInfo.province_id)) {
					uni.$u.toast('请选择所在地区');
					return false;
				}
				return true;
			},
			
			// 下一步
			nextStep(){
				if (this.ruleValidation()){
					this.$set(this.ocrLicenseInfo, "image", this.halfRoadRoute);
					this.$set(this.ocrLicenseInfo, "addressAll", this.addressAll);
					console.log(this.ocrLicenseInfo);
					uni.setStorageSync('ocrLicenseInfo',this.ocrLicenseInfo)
					uni.navigateTo({
						url:'/pagesMy/businessJoin/joinApplyThree' 
					})
				}
			},
			// 确认修改
			confirmModify(){
				if (this.ruleValidation()){
					this.$set(this.ocrLicenseInfo, "image", this.halfRoadRoute);
					console.log(this.ocrLicenseInfo);
					uni.setStorageSync('ocrLicenseInfo',this.ocrLicenseInfo)
					uni.setStorageSync('yyzzShow',true)
					uni.navigateBack({
						delta: 1
					})
				}
			}
		},
		// 页面滚动
		onPageScroll: function(e) {
			const scrollTop = e.scrollTop; // 获取页面滚动位置
			// 根据滚动位置修改状态栏样式
			if (scrollTop > 20) {
				this.backgroundColor = '#ffffff';
			} else {
				this.backgroundColor = '';
			}
			// console.log("滚动距离为：" + e.scrollTop);
		},
	}
</script>

<style scoped>
	.module {
		width: 750rpx;
		margin: 0 auto;
	}
	.custom_box {
		width: 750rpx;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9;
		padding-bottom: 10rpx;
		opacity: 1;
	}

	.indexbg {
		position: absolute;
		top: 0;
		left: 0;
		width: 750rpx;
		height: 260rpx;
		z-index: 7;
	}

	.custom_nav {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 750rpx;
		font-size: 36rpx;
		z-index: 9;
		color: #FFFFFF;
	}

	.goback {
		position: absolute;
		left: 30rpx;
		text-align: center;
		width: 40rpx;
		height: 40rpx;
	}

	.information_txt {
		width: 686rpx;
		padding: 16rpx  0;
	}


	.content {
		width: 686rpx;
		box-shadow: inset 0rpx -1rpx 0rpx 0rpx rgba(0,0,0,0.05);
		margin: 30rpx 0 10rpx;
	}

	.content_tip {
		font-size: 20rpx;
		color: #999999;
		margin: 10rpx 0 20rpx;
	}
	.content_r{
		width: 690rpx;
		height: 390rpx;
		/* border: 1rpx solid rgba(0,0,0,0.1); */
		border-radius: 20rpx;
		margin: 0 auto;
	}
	.content_r>image{
		width: 600rpx;
		height: 360rpx;
	}
	.term_box{
		width: 686rpx;
		margin: 30rpx 0 20rpx;
	}
	.padb30{
		padding-bottom: 30rpx;
	}
	.tishi {
		font-size: 28rpx;
		color: #FA6E01;
		margin-left: 6rpx;
	}
.xuanze {
		padding: 10rpx 0 20rpx;
	}

	.btns {
		position: fixed;
		bottom: 0rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 690rpx;
		height: 150rpx;
		background: #f8f8f8;
	}

	.sign_out {
		width: 158rpx;
		height: 88rpx;
		font-size: 32rpx;
		color: #333333;
		line-height: 88rpx;
		text-align: center;
		background: #FFFFFF;
		font-weight: 500;
		border-radius: 20rpx;
		border: 2rpx solid rgba(153, 153, 153, 0.18);
	}

	.service {
		width: 504rpx;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 32rpx;
		color: #333333;
		font-weight: 500;
		text-align: center;
		background: #FFCC28;
		border-radius: 20rpx;
	}
	.service2 {
		width: 690rpx;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 32rpx;
		color: #333333;
		font-weight: 500;
		text-align: center;
		background: #FFCC28;
		border-radius: 20rpx;
	}
	.change_state {
		font-size: 28rpx;
		color: #c0c4cc;
	}
	.active {
		font-size: 28rpx;
		color: #666666 !important;
	}
	/deep/.u-upload__wrap{
		margin: 0 auto !important;
	}
	/deep/.u-input__content {
		margin-left: -20rpx;
	}
	
	/deep/.u-upload__deletable {
		height: 24px !important;
		width: 24px !important;
	}
	
	/deep/.u-icon__icon {
		font-size: 30rpx !important;
		line-height: 30rpx !important;
	}
	/* #ifdef MP-ALIPAY */
	/deep/.u-input__content__field-wrapper__field{
		background: transparent!important;
	}
	/* #endif */
</style>